package com.quectel.core.module.scheduling.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.scheduling.SchedulingAttendanceGroupConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.scheduling.dao.SchedulingAttendanceGroupPersonWorkTimeConfigDao;
import com.quectel.core.module.scheduling.dto.FixWorkTimeBindingDto;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceGroupDto;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceGroupPersonWorkTimeConfigDto;
import com.quectel.core.module.scheduling.dto.SchedulingTimeConfigDto;
import com.quectel.core.module.scheduling.entity.SchedulingAttendanceGroupPersonWorkTimeConfigEntity;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceGroupPersonBindingService;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceGroupPersonWorkTimeConfigService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@DubboService
public class SchedulingAttendanceGroupPersonWorkTimeConfigServiceImpl implements SchedulingAttendanceGroupPersonWorkTimeConfigService{

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingAttendanceGroupPersonWorkTimeConfigServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SCHEDULING_ATTENDANCE_GROUP_PERSON_WORK_TIME_CONFIG_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SCHEDULING_ATTENDANCE_GROUP_PERSON_WORK_TIME_CONFIG_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<SchedulingAttendanceGroupPersonWorkTimeConfigDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(SCHEDULING_ATTENDANCE_GROUP_PERSON_WORK_TIME_CONFIG_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private SchedulingAttendanceGroupPersonWorkTimeConfigDao schedulingAttendanceGroupPersonWorkTimeConfigDao;
    @Autowired
    private SchedulingAttendanceGroupPersonWorkTimeConfigService schedulingAttendanceGroupPersonWorkTimeConfigService;
    @Autowired
    private SchedulingAttendanceGroupPersonBindingService schedulingAttendanceGroupPersonBindingService;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void savePersonWorkTime(List<SchedulingAttendanceGroupPersonWorkTimeConfigDto> saveDtoList, List<Long> personWorkTimeIds) {

        // 删除关联的id记录
        for (Long personWorkTimeId : personWorkTimeIds) {
            deleteById(personWorkTimeId);
        }

        // 保存新数据 人 天 时间段
        for (SchedulingAttendanceGroupPersonWorkTimeConfigDto configDto : saveDtoList) {
            schedulingAttendanceGroupPersonWorkTimeConfigService.save(configDto);
        }
    }

    /**
     * 此方法是查询手动排班的一条记录 索引搜索数据库中此三个字段有索引
     * @param schedulingAttendanceGroupId 考勤组id
     * @param personId 人员id
     * @param date 排班日期
     * @return
     */
    @Override
    public SchedulingAttendanceGroupPersonWorkTimeConfigDto selectOneByUkCols(Long schedulingAttendanceGroupId, Long personId, Date date) {
        SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = schedulingAttendanceGroupPersonWorkTimeConfigDao
                .selectOne(new LambdaQueryWrapper<SchedulingAttendanceGroupPersonWorkTimeConfigEntity>()
                        .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getSchedulingAttendanceGroupId, schedulingAttendanceGroupId)
                        .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getPersonId, personId)
                        .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getDate, date)
                );
        return paddingField(CopyUtils.copyObj(entity, SchedulingAttendanceGroupPersonWorkTimeConfigDto.class));
    }

    /**
     * 此方法是用于查询固定班的记录
     * @param schedulingAttendanceGroupId
     * @return
     */
    @Override
    public SchedulingAttendanceGroupPersonWorkTimeConfigDto selectOne(Long schedulingAttendanceGroupId) {
        SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = schedulingAttendanceGroupPersonWorkTimeConfigDao
                .selectOne(new LambdaQueryWrapper<SchedulingAttendanceGroupPersonWorkTimeConfigEntity>()
                .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getSchedulingAttendanceGroupId, schedulingAttendanceGroupId)
                .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        return paddingField(CopyUtils.copyObj(entity, SchedulingAttendanceGroupPersonWorkTimeConfigDto.class));
    }

    @Override
    public List<SchedulingTimeConfigDto> workTime(Long personId, String dateStr) {
        SchedulingAttendanceGroupDto schedulingAttendanceGroupDto = schedulingAttendanceGroupPersonBindingService.selectGroupByPersonId(personId);
        if (Objects.isNull(schedulingAttendanceGroupDto)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<SchedulingAttendanceGroupPersonWorkTimeConfigEntity> wrapper = new LambdaQueryWrapper<SchedulingAttendanceGroupPersonWorkTimeConfigEntity>()
                .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getSchedulingAttendanceGroupId, schedulingAttendanceGroupDto.getId())
                .eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getPersonId, personId);
        if (SchedulingAttendanceGroupConstants.SchedulingTypeEnum.SCHEDULING.getType().equals(schedulingAttendanceGroupDto.getShiftSystemType())) {
            wrapper.eq(SchedulingAttendanceGroupPersonWorkTimeConfigEntity::getDate, dateStr);
        }
        wrapper.last(SqlConstants.MYSQL_LIMIT_ONE);
        SchedulingAttendanceGroupPersonWorkTimeConfigEntity schedulingAttendanceGroupPersonWorkTimeConfigEntity = schedulingAttendanceGroupPersonWorkTimeConfigDao.selectOne(wrapper);
        if (Objects.isNull(schedulingAttendanceGroupPersonWorkTimeConfigEntity)
                || StringUtils.isBlank(schedulingAttendanceGroupPersonWorkTimeConfigEntity.getTimeConfigArr())) {
            return Lists.newArrayList();
        }
        if (SchedulingAttendanceGroupConstants.SchedulingTypeEnum.SCHEDULING.getType().equals(schedulingAttendanceGroupDto.getShiftSystemType())) {
            return JacksonUtils.parseArray(schedulingAttendanceGroupPersonWorkTimeConfigEntity.getTimeConfigArr(), SchedulingTimeConfigDto.class);
        } else if (SchedulingAttendanceGroupConstants.SchedulingTypeEnum.FIX.getType().equals(schedulingAttendanceGroupDto.getShiftSystemType())) {
            List<FixWorkTimeBindingDto> fixWorkTimeBindingDtos = JacksonUtils.parseArray(schedulingAttendanceGroupPersonWorkTimeConfigEntity.getTimeConfigArr(), FixWorkTimeBindingDto.class)
                    .parallelStream()
                    .collect(Collectors.groupingBy(FixWorkTimeBindingDto::getDay))
                    .get(DateUtil.dayOfWeekEnum(DateUtils.parse(dateStr, DateUtils.FormatType.SIMPLE)).getValue());
            if (CollectionUtils.isNotEmpty(fixWorkTimeBindingDtos) && CollectionUtils.isNotEmpty(fixWorkTimeBindingDtos.get(0).getTimeConfigDtoList())) {
                return fixWorkTimeBindingDtos.get(0).getTimeConfigDtoList();
            }
        }
        return Lists.newArrayList();
    }

    @Override
    public SchedulingAttendanceGroupPersonWorkTimeConfigDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SCHEDULING_ATTENDANCE_GROUP_PERSON_WORK_TIME_CONFIG_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SchedulingAttendanceGroupPersonWorkTimeConfigDto selectById(Long id){
            SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = schedulingAttendanceGroupPersonWorkTimeConfigDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,SchedulingAttendanceGroupPersonWorkTimeConfigDto.class));
    }

    @Override
    public List<SchedulingAttendanceGroupPersonWorkTimeConfigDto> queryList(Map<String,Object> params){
        List<SchedulingAttendanceGroupPersonWorkTimeConfigEntity> list = schedulingAttendanceGroupPersonWorkTimeConfigDao.queryList(params);
        List<SchedulingAttendanceGroupPersonWorkTimeConfigDto> result =  CopyUtils.copyList(list,SchedulingAttendanceGroupPersonWorkTimeConfigDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<SchedulingAttendanceGroupPersonWorkTimeConfigDto> queryListWithoutPadding(Map<String,Object> params){
        List<SchedulingAttendanceGroupPersonWorkTimeConfigEntity> list = schedulingAttendanceGroupPersonWorkTimeConfigDao.queryList(params);
        return CopyUtils.copyList(list,SchedulingAttendanceGroupPersonWorkTimeConfigDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private SchedulingAttendanceGroupPersonWorkTimeConfigDto paddingField(SchedulingAttendanceGroupPersonWorkTimeConfigDto dto){
        if (dto != null){

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return schedulingAttendanceGroupPersonWorkTimeConfigDao.queryTotal(params);
    }

    @Override
    public Long save(SchedulingAttendanceGroupPersonWorkTimeConfigDto dto){
        SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceGroupPersonWorkTimeConfigEntity.class);
        entity.setId(Snowflake.nextId());
        schedulingAttendanceGroupPersonWorkTimeConfigDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SchedulingAttendanceGroupPersonWorkTimeConfigDto dto){
        SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceGroupPersonWorkTimeConfigEntity.class);

        schedulingAttendanceGroupPersonWorkTimeConfigDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(SchedulingAttendanceGroupPersonWorkTimeConfigDto dto) {
       SchedulingAttendanceGroupPersonWorkTimeConfigEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceGroupPersonWorkTimeConfigEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, schedulingAttendanceGroupPersonWorkTimeConfigDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        schedulingAttendanceGroupPersonWorkTimeConfigDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
